from typing import Dict, Any
from urllib.parse import urlparse
import time
import pymysql
from neo4j import GraphDatabase
from .mysql import get_mysql
from .redis import get_redis
from .milvus import get_milvus
from .neo4j import get_neo4j
from intelli_port.commons.observability import dependency_check_latency_ms, dependency_up


def health_snapshot() -> Dict[str, Any]:
    ok_mysql = False
    pool = get_mysql()
    if pool:
        try:
            t0 = time.time()
            conn = pool.acquire()
            cur = conn.cursor()
            cur.execute("SELECT 1")
            cur.close()
            pool.release(conn)
            ok_mysql = True
            dependency_check_latency_ms.labels(name="mysql").observe(max(0, (time.time() - t0) * 1000))
            dependency_up.labels(name="mysql").set(1)
        except Exception:
            ok_mysql = False
            dependency_up.labels(name="mysql").set(0)
    ok_redis = False
    try:
        t0 = time.time()
        client = get_redis()
        ok_redis = bool(client.ping())
        dependency_check_latency_ms.labels(name="redis").observe(max(0, (time.time() - t0) * 1000))
        dependency_up.labels(name="redis").set(1 if ok_redis else 0)
    except Exception:
        ok_redis = False
        dependency_up.labels(name="redis").set(0)
    ok_milvus = False
    mc = get_milvus()
    if mc:
        try:
            t0 = time.time()
            if hasattr(mc, "_channel"):
                ok_milvus = True
            dependency_check_latency_ms.labels(name="milvus").observe(max(0, (time.time() - t0) * 1000))
            dependency_up.labels(name="milvus").set(1 if ok_milvus else 0)
        except Exception:
            ok_milvus = False
            dependency_up.labels(name="milvus").set(0)
    ok_neo4j = False
    driver = get_neo4j()
    if driver:
        try:
            t0 = time.time()
            driver.verify_connectivity()
            ok_neo4j = True
            dependency_check_latency_ms.labels(name="neo4j").observe(max(0, (time.time() - t0) * 1000))
            dependency_up.labels(name="neo4j").set(1)
        except Exception:
            ok_neo4j = False
            dependency_up.labels(name="neo4j").set(0)
    return {"mysql": ok_mysql, "redis": ok_redis, "milvus": ok_milvus, "neo4j": ok_neo4j}